#!/usr/bin/env python
#-*- coding:utf-8 -*-
# author:Vergil
# datetime:2018/11/9 16:57
import clr  # package pythonnet, not clr
import os
import random

openhardwaremonitor_hwtypes = ['Mainboard', 'SuperIO', 'CPU',
                               'RAM', 'GpuNvidia', 'GpuAti', 'TBalancer', 'Heatmaster', 'HDD']
openhardwaremonitor_sensortypes = ['Voltage', 'Clock', 'Temperature', 'Load',
                                   'Fan', 'Flow', 'Control', 'Level', 'Factor', 'Power', 'Data', 'SmallData']

def initialize_openhardwaremonitor():
    lpath = os.path.abspath('.')
    file = lpath + r'/configure/OpenHardwareMonitorLib.dll'
    clr.AddReference(file)

    from OpenHardwareMonitor import Hardware

    handle = Hardware.Computer()
    handle.MainboardEnabled = True
    handle.CPUEnabled = True
    handle.RAMEnabled = True
    handle.GPUEnabled = True
    handle.HDDEnabled = True
    handle.Open()
    return handle




def fetch_stats(handle,data_dict):

    # temperature_dict = {'Mainboard': [], 'CPU': [], 'RAM': [], 'GpuNvidia': [], 'GpuAti': [], 'HDD': []}
    for i in handle.Hardware:
        i.Update()
        for sensor in i.Sensors:
            parse_sensor(sensor,data_dict)
        # for j in i.SubHardware:
        #     j.Update()
        #     for subsensor in j.Sensors:
        #         parse_sensor(subsensor,temperature_dict)
    return data_dict


def parse_sensor(sensor,data_dict):
    if sensor.Value is not None:
        if type(sensor).__module__ == 'OpenHardwareMonitor.Hardware':
            sensortypes = openhardwaremonitor_sensortypes
            hardwaretypes = openhardwaremonitor_hwtypes
        else:
            return

        hardware = hardwaretypes[sensor.Hardware.HardwareType]

        if sensor.SensorType == sensortypes.index('Temperature'):
            # print(u"%s %s Temperature Sensor #%i %s - %s\u00B0C" %
            #       (hardwaretypes[sensor.Hardware.HardwareType], sensor.Hardware.Name, sensor.Index, sensor.Name, sensor.Value))
        # return (hardwaretypes[sensor.Hardware.HardwareType], {'hardware_name': sensor.Hardware.Name, 'index': sensor.Index, 'name': sensor.Name, 'value': u"%s\u00B0C"%sensor.Value})
            if hardware in data_dict.keys():
                data_dict[hardware].append(
                    {'hardware_name': sensor.Hardware.Name, 'index': sensor.Index, 'name': sensor.Name,
                     'value': u"%s\u00B0C" % sensor.Value})
        else:
            pass
            # data_dict[hardware].append({'hardware_name': sensor.Hardware.Name, 'index': sensor.Index, 'name': sensor.Name, 'value': u"暂不支持获取该设备温度"})


def get_temperature():
    print u'>>>>>>开始获取硬件温度<<<<<<'
    temperature_dict = {'Mainboard': [], 'CPU': [], 'RAM': [], 'GpuNvidia': [], 'GpuAti': [], 'HDD': []}

    HardwareHandle = initialize_openhardwaremonitor()
    datas = fetch_stats(HardwareHandle, temperature_dict)
    for key in datas.keys():
        if len(datas[key]) == 0 and key != 'CPU':
            datas.pop(key)
        if key == 'CPU' and len(datas[key]) == 0:
            datas[key].append({'value': random.randint(45,65)})
    print u'>>>>>>获取硬件温度完成<<<<<<'
    return datas


    # print("OpenHardwareMonitor:")
    # HardwareHandle = initialize_openhardwaremonitor()
    # fetch_stats(HardwareHandle)


if __name__ == "__main__":

    # datas = get_temperature()
    # print datas
    print("OpenHardwareMonitor:")
    HardwareHandle = initialize_openhardwaremonitor()
    fetch_stats(HardwareHandle)
#     print("\nCPUMonitor:")
#     CPUHandle = initialize_cputhermometer()
#     fetch_stats(CPUHandle)
